//
//  UIWidgetViewer.m
//  FloatingWidget
//
//  Created by silent on 10. 3. 11..
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UIWidgetViewer.h"


@implementation UIWidgetViewer


- (UIView *)findUIWebDocumentView{
	UIView *webDocumentView = nil;
	NSString *className;
	UIView *scroller = [[webView subviews] objectAtIndex:0];
	for(UIView *view in [scroller subviews]){
		className = [NSString stringWithFormat:@"%@", [view class]];
		NSLog(@"found a %@", className);
		if([className isEqualToString:@"UIWebDocumentView"]){ 
			NSLog(@"found the UIWebDocumentView");
			webDocumentView = view;
		}
	}
	return webDocumentView;
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
		CGRect rect = CGRectMake(1, 1, frame.size.width-2, frame.size.height-2);
		webView = [[UIWebView alloc] initWithFrame:rect];
		webView.scalesPageToFit = YES;
		[self addSubview:webView];
		
		rect = CGRectMake(0, 0, frame.size.width, frame.size.height);
		panelView = [[UIView alloc] initWithFrame:rect]; 
		[self addSubview:panelView];
		
		documentView = [self findUIWebDocumentView];
    }
    return self;
}


- (void)drawRect:(CGRect)rect {
    // Drawing code
//	[super drawRect:rect];
	 
//	NSLog(@"x:%3f y:%3f w:%3f h:%3f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
//	[webView setNeedsDisplay];
}


- (void)dealloc {
	[panelView release];
	[webView release];
    [super dealloc];
}

#pragma mark -
- (void)setURL:(NSString *)urlString {
	NSURL *url = [NSURL URLWithString:urlString];
	NSURLRequest *request = [NSURLRequest requestWithURL:url];
	[webView loadRequest:request];
}

#pragma mark -
CGPoint startLocation;

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"touchesBegan");
	// Retrieve the touch point
	CGPoint pt = [[touches anyObject] locationInView:self];
	startLocation = pt;
	[[self superview] bringSubviewToFront:self];
	
	[documentView touchesBegan:touches withEvent:event];
}
- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
	[documentView touchesCancelled:touches withEvent:event];
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	[documentView touchesEnded:touches withEvent:event];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"touchesMoved");
	// Move relative to the original touch point
//	CGPoint pt = [[touches anyObject] locationInView:self];
//	CGRect frame = [self frame];
//	frame.origin.x += pt.x - startLocation.x;
//	frame.origin.y += pt.y - startLocation.y;
//	[self setFrame:frame];
	
	[documentView touchesMoved:touches withEvent:event];

}

@end
